#!/bin/sh -e
# {{ ansible_managed }}

# Get an OSCP response from the certificates OCSP issuer for use
# with HAProxy, then reload HAProxy if there have been updates.

# Path to certificates
PEMSDIR={{ haproxy_config_crt_base }}

UPDATED=0

cd ${PEMSDIR}
for pem in *.pem; do

	# Get the OCSP URL from the certificate
	ocsp_url=$(openssl x509 -noout -ocsp_uri -in $pem)

	# Only process OCSP if URL was present
	if [ "${ocsp_url}" != "" ]; then
		# Extract the hostname from the OCSP URL
		ocsp_host=$(echo $ocsp_url | cut -d/ -f3)

		# Only process the certificate if we have a .issuer file
		if [ -r ${pem}.issuer ]; then

			# Request the OCSP response from the issuer and store it
			openssl ocsp \
				-issuer ${pem}.issuer \
				-cert ${pem} \
				-url ${ocsp_url} \
				-header Host ${ocsp_host} \
				-respout ${pem}.ocsp
		fi
		UPDATED=$(( $UPDATED + 1 ))
	fi
done

if [ $UPDATED -gt 0 ]; then
	service {{ haproxy_service_name }} reload
fi
